//
//  EditDataViewController.m
//  SeaMelonSeeds_Counselor
//
//  Created by 尤振宇 on 2017/7/18.
//  Copyright © 2017年 杨笑. All rights reserved.
//

#import "EditDataViewController.h"
#import "UIButton+LayoutEdgeInsets.h"
#import "EditView.h"
#import "TagSelectionViewController.h"
#import <SDWebImage/UIButton+WebCache.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "ConsultantInformation.h"
#import "UpLoadImageApi.h"
#import "ModifyProfileApi.h"

@interface EditDataViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property(nonatomic,strong)UIButton *changeBtn;
@property(nonatomic,strong)NSMutableArray *views;
@property(nonatomic,strong)UIImagePickerController *imagePicker;


@property(nonatomic,weak)UIImageView *imageView;
@property(nonatomic,assign)int imageViewIndex;//表明反正面
@property(nonatomic,strong)NSMutableArray *updataImages;
@property(nonatomic,strong)UIImage *updateAvatar;

@property(nonatomic,weak)UITextField *nameTF;
@property(nonatomic,weak)UITextField *yearTF;
@property(nonatomic,weak)IQTextView *summaryTV;

@property(nonatomic,strong)ConsultantInformation *uploadInfo;
@end

@implementation EditDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.uploadInfo  = [ConsultantInformation new];
    
    self.title = @"个人信息";
    self.view.backgroundColor = [UIColor whiteColor];
    [self initView];
    
    self.navigationItem.rightBarButtonItem = [Tool BarButtonItemWithTitle:@"提交" target:self action:@selector(submit)];

    [self.changeBtn sd_setImageWithURL:[NSURL URLWithString:[ConsultantInformation sharedInformation].avatar] forState:(UIControlStateNormal)];
}



-(void)submit
{
    WeakSelf(self)
    if ([self.nameTF hasText]) {
        self.uploadInfo.name = self.nameTF.text;
    }
    if ([self.yearTF hasText]) {
        self.uploadInfo.years = [self.yearTF.text intValue];
    }
    if ([self.summaryTV hasText]) {
        self.uploadInfo.summary = self.summaryTV.text;
    }
    
    
    ModifyProfileApi *api = [[ModifyProfileApi alloc] initWithInfo:self.uploadInfo];
    api.needHUD = YES;
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (kCode(request.responseJSONObject)) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"资料提交成功，等待管理员审核" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakself.navigationController popViewControllerAnimated:YES];
            }]];
            [weakself presentViewController:alert animated:YES completion:nil];
            
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
    }];
}

-(void)selectImage:(UIButton *)btn
{
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

-(void)initView
{
    
    UIImage *image = [UIImage imageNamed:@"My_TheDefaultAvatar"];
    [self.changeBtn roundedCorners:image.size.width/2];
    CGFloat btn_H = image.size.height;
    
    [self.changeBtn setImage:image forState:(UIControlStateNormal)];
    [self.changeBtn setImage:image forState:(UIControlStateDisabled)];
    [self.changeBtn addTarget:self action:@selector(selectImage:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.scrollView addSubview:self.changeBtn];
    [self.changeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView).with.offset(20);
        make.centerX.equalTo(self.scrollView);
        make.width.mas_equalTo(btn_H);
        make.height.mas_equalTo(btn_H);
    }];
    
    UILabel *label = [UILabel new];
    label.text = @"请上传一张正面免冠照";
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = k666666;
    [self.scrollView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.changeBtn.mas_bottom);
        make.centerX.equalTo(self.changeBtn);
        make.height.equalTo(@20);
    }];
    
    
    for (int i =0; i<self.views.count; i++) {
        EditView *view = [self.views objectAtIndex:i];
        [self.scrollView addSubview:view];
        
        EditView *onview;
        if (i > 0) {
            onview = [self.views objectAtIndex:i-1];
        }
        
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            if (onview) {
                make.top.equalTo(onview.mas_bottom);
            }else{
                make.top.equalTo(self.changeBtn.mas_bottom).with.offset(20);
            }
            make.left.equalTo(self.scrollView);
            make.width.equalTo(self.scrollView);
            
            if (i == self.views.count - 1) {
                make.bottom.equalTo(self.scrollView).with.offset(-20);
                make.height.mas_equalTo(@180);
            }
        }];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)pushSelect:(NSArray <TagSelection* >*)tags multiSelect:(BOOL)multiSelect SelectData:(SelectData)selectData title:(NSString *)title
{
    TagSelectionViewController *vc = [[TagSelectionViewController alloc]initWithData:tags multiSelect:multiSelect selectData:selectData];
    vc.title = title;
    [vc.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor]} forState:(UIControlStateNormal)];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo
{
    if (self.imageView) {
        [self.updataImages removeObject:self.imageView.image];
        self.imageView.image = image;
        [self.updataImages addObject:image];
        
        WeakSelf(self)
        
        UpLoadImageApi *api = [[UpLoadImageApi alloc] initWithImage:image];
        api.needHUD = YES;
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            if (kCode(request.responseJSONObject)) {
                //更新
                if (weakself.imageViewIndex == 0) {
                    weakself.uploadInfo.qualifications_up = request.responseJSONObject[@"data"][@"url"];
                }else{
                    weakself.uploadInfo.qualifications_down = request.responseJSONObject[@"data"][@"url"];
                }
            }
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
        
    }else{
        self.updateAvatar = image;
        [self.changeBtn setImage:image forState:(UIControlStateNormal)];
        WeakSelf(self)
        
        UpLoadImageApi *api = [[UpLoadImageApi alloc] initWithImage:image];
        api.needHUD = YES;
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            if (kCode(request.responseJSONObject)) {
                //更新
                weakself.uploadInfo.avatar = request.responseJSONObject[@"data"][@"url"];
            }
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
        
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.imageView = nil;
    
}

-(UIButton *)changeBtn
{
    if (!_changeBtn) {
        _changeBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _changeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _changeBtn.enabled = self.editor;
    }
    return _changeBtn;
}

- (UIImagePickerController *)imagePicker
{
    if (_imagePicker == nil) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.modalPresentationStyle = UIModalPresentationOverFullScreen;
        _imagePicker.delegate = self;
        _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
    }
    
    return _imagePicker;
}



-(NSMutableArray *)views
{
    if (!_views) {
        ConsultantInformation *info = [ConsultantInformation sharedInformation];
        
        _views = [NSMutableArray array];
        NSArray *texts = @[@"姓名",@"性别",@"咨询师职称",@"医院职称",@"工作年限",@"擅长领域",@"从业资质",@"个人简介"];
        NSArray *types = @[@(TextField_EditViewType),@(Button_EditViewType),@(Button_EditViewType),@(Button_EditViewType),@(TextField_EditViewType),@(Button_EditViewType),@(ImageView_EditViewType),@(TextView_EditViewType)];
        WeakSelf(self)
        for (int i = 0; i < texts.count; i++) {
            NSString *str = texts[i];
            
            EditView *view = [[EditView alloc]initWithType:[types[i] integerValue]];
            view.label.text = str;
            [_views addObject:view];
            WeakSelf(view)
            
            if (i == 0) {
                //姓名
                view.textField.placeholder = @"真实姓名";
                view.textField.enabled = self.editor;
                
                view.textField.text = info.name;
                self.nameTF = view.textField;
                
            }else if (i == 1){
                //性别
                view.btn.enabled = self.editor;
                
                NSString *sex = info.sex?@"女":@"男";
                [view.btn setTitle:sex forState:UIControlStateNormal];

                view.buttonAction = ^(id obj) {
                    
                    TagSelection *tag1 = [[TagSelection alloc]init];
                    tag1.name = @"男";
                    tag1.id = 1;
                    
                    TagSelection *tag2 = [[TagSelection alloc]init];
                    tag2.name = @"女";
                    tag2.id = 0;
                    
                    [weakself pushSelect:@[tag1,tag2] multiSelect:NO SelectData:^(NSArray<TagSelection *> *datas) {
                        
                        TagSelection* model = [datas firstObject];
                        [weakview.btn setTitle:model.name forState:UIControlStateNormal];
                        //更新
                        weakself.uploadInfo.sex = model.id;
                        
                    } title:texts[i]];
                    
                };
            }else if (i == 2){
                //咨询师职称
                view.btn.enabled = self.editor;
                
                [view.btn setTitle:info.counselor_title == 0 ? @"请选择" : info.consultantTitle forState:UIControlStateNormal];
                view.buttonAction = ^(id obj) {
                    NSArray *allTitles = [Tool AllConsultantTitle];
                    [weakself pushSelect:allTitles multiSelect:NO SelectData:^(NSArray<TagSelection* > *datas) {
                        
                        TagSelection* model = [datas firstObject];
                        [weakview.btn setTitle:model.name forState:UIControlStateNormal];
                        //更新
                        weakself.uploadInfo.counselor_title = model.id;
                        
                    } title:texts[i]];
                };
            }else if (i == 3){
                //医院职称
                view.btn.enabled = self.editor;
                
                [view.btn setTitle:info.hospital_title == 0 ? @"请选择" : info.hospitalTitle forState:UIControlStateNormal];
                view.buttonAction = ^(id obj) {
                    NSArray *allTitles = [Tool AllHospitalTitle];
                    [weakself pushSelect:allTitles multiSelect:NO SelectData:^(NSArray<TagSelection *> *datas) {
                        
                        TagSelection*  model = [datas firstObject];
                        [weakview.btn setTitle:model.name forState:UIControlStateNormal];
                        //更新
                        weakself.uploadInfo.hospital_title = model.id;
                        
                    } title:texts[i]];
                };
            }else if (i == 4){
                //工作年限
                view.textField.placeholder = @"工作年限";
                view.textField.enabled = self.editor;
                
                view.textField.text = [NSString stringWithFormat:@"%ld",info.years];
                view.textField.keyboardType = UIKeyboardTypeNumberPad;
                self.yearTF = view.textField;
            }else if (i == 5){
                //擅长领域
                view.btn.enabled = self.editor;
                
                
                [view.btn setTitle:@"请选择" forState:UIControlStateNormal];
                view.buttonAction = ^(id obj) {
                   
                    NSArray *allTitles = [Tool AllSkilledfieldTitle];
                    [weakself pushSelect:allTitles multiSelect:YES SelectData:^(NSArray<TagSelection* > *datas) {
                        NSString *str = @"";
                        NSMutableArray *array = [NSMutableArray new];
                        for (TagSelection *model in datas) {
                          str = [NSString stringWithFormat:@"%@%@,",str,model.name];
                            [array addObject:@(model.id)];
                        }
                        if ([str length] > 0) {
                            [weakview.btn setTitle:str forState:UIControlStateNormal];
                            //更新
                            weakself.uploadInfo.fields = array;
                        }else{
                            [weakview.btn setTitle:@"请选择" forState:UIControlStateNormal];
                        }
                        
                        
                        
                    } title:texts[i]];
                };
            }else if (i == 6){
                //从业资质
                view.imageView1.userInteractionEnabled = self.editor;
                view.imageView2.userInteractionEnabled = self.editor;
                
                view.selectImageAction = ^(UIImageView *obj,int index) {
                    weakself.imageView = obj;
                    weakself.imageViewIndex = index;
                    [weakself selectImage:nil];
                };
                
                [view.imageView1 sd_setImageWithURL:[NSURL URLWithString:info.qualifications_up] placeholderImage:[UIImage imageNamed:@"selectImageIcon"]];
                [view.imageView2 sd_setImageWithURL:[NSURL URLWithString:info.qualifications_down] placeholderImage:[UIImage imageNamed:@"selectImageIcon"]];
            }else if (i == 7){
                //个人简介
                view.textView.placeholder = @"个人简介";
                view.textView.editable = self.editor;
                view.textView.font = [UIFont systemFontOfSize:14];
                
                view.textView.text = info.summary;
                self.summaryTV = view.textView;
            }
        }
    }
    return _views;
}

-(NSMutableArray *)updataImages
{
    if (!_updataImages) {
        _updataImages = [NSMutableArray array];
    }
    return _updataImages;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
